package com.example.hosptial.newController;

import com.example.hosptial.model.enity.Admin;
import com.example.hosptial.model.enity.Department;
import com.example.hosptial.model.enity.Doctor;
import com.example.hosptial.model.view.DoctorView;
import com.example.hosptial.service.DoctorManagementService;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 医生管理Controller
 * 处理管理员对医生信息的管理请求
 */
@Controller
@RequestMapping("/admin")
public class DoctorManagementController {

    private static final Logger logger = LoggerFactory.getLogger(DoctorManagementController.class);

    @Autowired
    private DoctorManagementService doctorManagementService;

    /**
     * 显示医生管理页面
     */
    @GetMapping("/doctor-manage")
    public String showDoctorManagePage(HttpSession session, Model model) {
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            return "redirect:/admin/auth/login";
        }
        return "admin/doctor-manage :: content";
    }

    /**
     * 获取所有科室列表
     */
    @GetMapping("/departments")
    @ResponseBody
    public List<Department> getDepartments() {
        logger.info("Getting all departments");
            List<Department> departments = doctorManagementService.getAllDepartments();
        logger.info("Found {} departments", departments.size());
        return departments;
    }

    /**
     * 获取医生列表
     */
    @GetMapping("/doctors")
    @ResponseBody
    public List<DoctorView> getDoctors(@RequestParam(required = false) Integer deptId) {
        if (deptId != null) {
            logger.info("Getting doctors for department ID: {}", deptId);
            List<DoctorView> doctors = doctorManagementService.getDoctorsByDepartment(deptId);
            logger.info("Found {} doctors in department {}", doctors.size(), deptId);
            return doctors;
        }
        logger.info("Getting all doctors");
        List<DoctorView> doctors = doctorManagementService.getAllDoctors();
        logger.info("Found {} doctors in total", doctors.size());
        return doctors;
    }

    /**
     * 添加新医生
     */
    @PostMapping("/addDoctor")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> addDoctor(@Valid @RequestBody Map<String, Object> doctorData, 
                                                       BindingResult bindingResult) {
        Map<String, Object> response = new HashMap<>();
        
        if (bindingResult.hasErrors()) {
            response.put("success", false);
            response.put("message", "输入数据验证失败");
            return ResponseEntity.badRequest().body(response);
        }
        
        try {
            // 创建医生实体
            Doctor doctor = new Doctor();
            doctor.setDoctorId((String) doctorData.get("doctorId"));
            doctor.setDoctorName((String) doctorData.get("doctorName"));
            doctor.setDoctorGender((String) doctorData.get("doctorGender"));
            doctor.setDoctorAge((Integer) doctorData.get("doctorAge"));
            doctor.setDoctorIdCard((String) doctorData.get("doctorIdCard"));
            doctor.setDoctorPhone((String) doctorData.get("doctorPhone"));
            
            // 设置默认密码（可以是身份证后6位）
            String defaultPassword = doctor.getDoctorIdCard().substring(12);
            doctor.setDoctorPassword(defaultPassword);
            
            // 设置科室
            Department department = new Department();
            department.setDeptId((Integer) doctorData.get("deptId"));
            doctor.setDepartment(department);

            // 保存医生信息
            Doctor savedDoctor = doctorManagementService.addDoctor(doctor);
            
            response.put("success", true);
            response.put("message", "医生添加成功");
            response.put("doctorId", savedDoctor.getDoctorId());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("添加医生失败", e);
            response.put("success", false);
            response.put("message", "添加医生失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 搜索医生
     */
    @GetMapping("/doctors/search")
    @ResponseBody
    public List<DoctorView> searchDoctors(@RequestParam String name) {
        return doctorManagementService.searchDoctorsByName(name);
    }
}